<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="450px" :title="`设置角色权限`">
    <div>
      <div class="flex-x-end">
        <el-button class="float-right" type="primary" @click="handleSubmit">确 定</el-button>
      </div>
      <div class="tree-content clear-both">
        <el-scrollbar>
          <el-tree
            ref="menuTree"
            :data="menuTreeData"
            :default-checked-keys="menuTreeIds"
            :props="{ label: 'title', children: 'childList' }"
            default-expand-all
            highlight-current
            node-key="id"
            show-checkbox
          >
            <template #default="{ node }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
    </div>
    <!-- <template #footer>
      <el-button @click="drawerVisible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template> -->
  </el-drawer>
</template>
<script setup lang="ts" name="MenuDrawer">
import { ref } from "vue";
import { System } from "@/api/interface";
import { ElMessage } from "element-plus";
interface DrawerProps {
  row: Partial<System.ResRoleList>;
  api?: (params: any) => Promise<any>;
  getRouterList?: (params: any) => Promise<any>;
  getRoleById?: (params: any) => Promise<any>;
}

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  row: {}
});
const menuTree = ref();
const menuTreeData = ref([]);
const menuTreeIds = ref([]);
const init = async () => {
  // 获取所有菜单树
  try {
    const res = await drawerProps.value!.getRouterList!({ pageNum: 1, pageSize: 1000 });
    menuTreeData.value = res.data.list;
    const res1 = await drawerProps.value!.getRoleById!({ id: drawerProps.value.row.id });

    menuTree.value.setCheckedKeys(res1.data.routerIds, true);
  } catch (error) {
    console.log("error:", error);
  }
};

// 接收父组件传过来的参数
const acceptParams = async (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
  init();
};

const handleSubmit = async () => {
  try {
    const checkArr = menuTree.value.getCheckedKeys(true);
    await drawerProps.value!.api!({ ...drawerProps.value.row, routerIds: checkArr });
    ElMessage.success({ message: `设置成功！` });
    drawerVisible.value = false;
  } catch (error) {
    console.log(error);
  }
};

defineExpose({
  acceptParams
});
</script>
